'use strict';

const qiniu = require('qiniu')

module.exports = app => {
  class HomeController extends app.Controller {
    async index() {
      await this.ctx.render('index.tpl');
    }

    async getLogin() {
      await this.ctx.render('login.tpl');
    }

    async login() {
      const { username, password } = this.ctx.request.body
      let user = await this.app.mysql.get('user', { name: username })
      let body
      if (!!user && (password === user.password)) {
        user = {
          id: user.id,
          username: user.name,
          realname: user.realname,
          login_at: new Date(),
        }
        this.ctx.session.user = user;
        body = { msg: 'ok', user }
      } else {
        body = { msg: 'password is incorrected' }
      }
      this.ctx.status = 200
      this.ctx.body = body
    }

    getLogout() {
      this.ctx.session = null;
      this.ctx.redirect('/');
    }

    logout() {
      this.ctx.session = null;
      this.ctx.status = 200
      this.ctx.body = { msg: 'ok' }
    }

    async test() {
      this.ctx.body = 'test haha'
    }

    async apitest() {
      this.ctx.body = 'apitest haha'
    }

    async uploadToken() {
      const accessKey = '124-3ufQr_10-051VjCGtFo2fZ74mf5LLodb03Nv';
      const secretKey = 'SfLHNKHd5Kw3FkU23eI-JjLV7-O24Jp7qRC0KYYa';
      const mac = new qiniu.auth.digest.Mac(accessKey, secretKey);

      const options = {
        scope: 'aqing',
      }
      const putPolicy = new qiniu.rs.PutPolicy(options)
      const uploadToken = putPolicy.uploadToken(mac)
      this.ctx.body = { token: uploadToken }
    }


  }
  return HomeController;
};
